<template>
  <div class="flow-footer g-flex-center-center" v-if="isShowOpBtn">
    <el-button @click="handleBack">返回</el-button>
    <template v-for="item in footerButtons" :key="item.action">
      <el-button
        :type="item.buttonType ? item.buttonType.toLowerCase() : 'primary'"
        @click="handleSubmit(item)"
        :loading="actionLoading"
        >{{ item.actionName }}</el-button
      >
    </template>
    <AuditDialog :title="rejectTitle" v-model:visible="rejectVisible" @submit="handleAuditSubmit" />
  </div>
</template>
<script lang="ts" setup name="FlowFooter">
import { ref, computed, defineProps, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getListFlowButton, postCompleteUserTask } from '@/apis/todo/flow';
import type {
  GetListFlowButtonResult,
  PostCompleteUserTaskParams
} from '@/apis/todo/model/flowModel';
import { useMessage } from '@/hooks/useMessage';
import { TodoTaskStatusEnum } from '@/constants/enum';
import AuditDialog from '../AuditDialog/index.vue';
import { objFilterEmptyString } from '@/utils';

interface FlowFooterProps {
  processInstanceId: string;
  flowContentRef: any;
  pageType: keyof typeof TodoTaskStatusEnum;
}
const props = defineProps<FlowFooterProps>();

const { createMessage, createConfirm } = useMessage();
const router = useRouter();
const actionLoading = ref(false);
const actionComment = ref('');
const rejectVisible = ref(false);
const rejectParams = ref<any>();
const rejectTitle = ref('');
/**
 * action按钮点击
 * @param item action的item
 */
async function handleSubmit(item: GetListFlowButtonResult) {
  try {
    console.log('handleSubmit flowContentRef.value', props.flowContentRef, item);
    // NOTE 如果要实现保存和提交的区分，用submit带入needValidForm参数来做
    let businessParams = await props.flowContentRef.submit(item.needValidForm);
    businessParams = objFilterEmptyString(businessParams);
    console.log('handleSubmit businessParams', businessParams);
    if (item.needComment) {
      rejectTitle.value = item.actionName;
      rejectParams.value = {
        item,
        businessParams
      };
      rejectVisible.value = true;
      return;
    } else {
      if (item.needValidForm) {
        createConfirm(
          item.action == 'SUBMIT' ? '确认提交填报？' : '提示',
          item.action == 'SUBMIT'
            ? '提交填报后将直接进入数据审核阶段，审核期间数据无法更改，建议确保填报数据准确无误。'
            : '是否确认该操作？',

          {
            iconType: 'warning',
            cancelButtonText: item.action == 'SUBMIT' ? '取消' : '否',
            confirmButtonText: item.action == 'SUBMIT' ? '提交' : '是',
            btnType: 'primary'
          }
        ).then(() => {
          handleSubmitReq(item, businessParams);
        });
      } else {
        handleSubmitReq(item, businessParams);
      }
    }
  } catch (error) {
    console.log('error', error);
  }
}

/**
 * 审核意见必填的action的提交操作
 * @param comment 审核意见
 */
function handleAuditSubmit(comment: string) {
  actionComment.value = comment;
  if (actionComment.value) {
    handleSubmitReq(rejectParams.value.item, rejectParams.value.businessParams);
  }
}

/**
 * 正式提交接口
 */
async function handleSubmitReq(item: GetListFlowButtonResult, businessParams?: any) {
  try {
    actionLoading.value = true;
    const params: PostCompleteUserTaskParams = {
      action: item.action,
      actionComment: actionComment.value,
      taskId: item.taskId,
      processInstanceId: item.processInstanceId,
      businessKey: item.businessKey,
      completeTask: item.completeTask ?? true
    };
    businessParams && (params['businessParams'] = objFilterEmptyString(businessParams));
    console.log('handleSubmit params', params);
    await postCompleteUserTask(params);
    createMessage.success('操作成功');
    setTimeout(() => {
      actionLoading.value = false;
      handleBack();
    }, 500);
  } catch (error) {
    console.log('error', error);
    actionLoading.value = false;
  }
}

function handleBack() {
  router.back();
}

const footerButtons = ref<GetListFlowButtonResult[]>([]);
async function getFooterButtons() {
  try {
    footerButtons.value = await getListFlowButton(props.processInstanceId);
    console.log('footerButtons', footerButtons.value);
  } catch (error) {
    console.log('error', error);
  }
}

// NOTE 展示操作按钮
const isShowOpBtn = computed(() => {
  // 待办、即将超时、已超时
  return ['PENDING', 'ABOUT_TO_EXPIRE', 'OUT_OF_TIME'].includes(props.pageType);
});

onMounted(() => {
  if (isShowOpBtn.value) {
    getFooterButtons();
  }
});
</script>
<style lang="scss" scoped>
.flow-footer {
  // z-index: 10;
  // position: fixed;
  // bottom: 0;
  // left: 0;
  // width: 100%;
  // height: 56px;
  // background: #ffffff;
  // box-shadow: 0px -2px 4px 0px #f5f9fa, 0px -2px 4px -4px #eceff0;
}
</style>
